<?php
/**
 * 全局共享寄存器
 * 提升程序效率，降低类耦合
 */
namespace SFramework;

class Registry extends \ArrayObject
{
	protected static $_registry = null;

	public function __construct()
	{
		parent::__construct(array(), parent::ARRAY_AS_PROPS);
	}


	public static function getInstance()
	{
		if (null === self::$_registry) {
			self::$_registry = new self();
		}
		return self::$_registry;
	}


	public static function set($index, $value)
	{
		$instance = self::getInstance();
		$instance->offsetSet($index, $value);
	}


	public static function get($index)
	{
		$instance = self::getInstance();
		if (!$instance->offsetExists($index)) {
			// 如果不存在，则尝试获取
			$methodName = 'get'. ucfirst(strtolower($index));
			if (method_exists('SFramework\Obtain', $methodName)) {
				self::set($index, Obtain::$methodName());
			} else {
				throw new SException\UnexpectedValue('索引项`'. $index .'`不存在');
			}
		}
		return $instance->offsetGet($index);
	}


	public static function isRegistered($index)
	{
		if (null === self::$_registry) {
			return false;
		}
		return self::$_registry->offsetExists($index);
	}
}
